package com.atguigu.service.base.handler.exception;

import com.atguigu.common.util.R;
import com.atguigu.service.base.exception.GuliException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 优先匹配更精确的异常
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler{

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        e.printStackTrace();
        return R.error().message("全局异常处理器：服务器内部发生了错误！").data("exception", e.getMessage());
    }

    /**
     * 特定异常
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public R error01(Exception e) {
        e.printStackTrace();
        return R.error().message("特定异常").data("exception", e.getMessage());
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(GuliException.class)
    @ResponseBody
    public R guliError(GuliException e) {
        // e.printStackTrace();
        log.error(e.getMsg(), e);
        // log.error(e.getMessage());
        return R
                .error()
                .code(e.getCode())
                .message(e.getMsg());
    }
}
